package com.uuedu.examant.base

import com.examinantsdk.base.AESUtils
import com.examinantsdk.base.http.RSABean
import com.google.gson.*
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.nio.charset.Charset

class DecryptInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val responseBody = response.body
        val source = responseBody?.source()
        if (responseBody != null) {
            try {
                source?.request(Long.MAX_VALUE)
                val buffer = source?.buffer
                val originalResponseString = buffer?.clone()?.readString(Charset.forName("UTF-8"))
                val result = Gson().fromJson(originalResponseString, RSABean::class.java)
                if (result != null) {
                    if (result.data?.encrypt?.isNotEmpty() == true) {
                        val decryptedBytes =
                            AESUtils().decrypt(result.data?.encrypt!!)
                        // 构造新的响应体
                        val decryptedJsonObject =
                            originalResponseString?.let {
                                Gson().fromJson(
                                    it,
                                    JsonObject::class.java
                                )
                            }
                        when (decryptedBytes.first()) {
                            '{' -> {
                                //如果是对象
                                val decryptedJsonObject2 =
                                    Gson().fromJson(decryptedBytes, JsonObject::class.java)
                                decryptedJsonObject?.add("data", decryptedJsonObject2)
                            }
                            '[' -> {
                                val jsonArray =
                                    Gson().fromJson(decryptedBytes, JsonArray::class.java)
                                decryptedJsonObject?.add("data", jsonArray)
                            }
                            else -> {
                                //如果解密之后的数据既不是对象，也不是数组而是基本数据类型，则这么处理
                                val jsonParser = JsonParser()
                                val decryptedJsonElement = jsonParser.parse(decryptedBytes)
                                if (decryptedJsonElement.isJsonPrimitive) {
                                    val decryptedJsonPrimitive =
                                        decryptedJsonElement.asJsonPrimitive
                                    if (decryptedJsonPrimitive.isBoolean) {
                                        val decryptedBoolean = decryptedJsonPrimitive.asBoolean
                                        decryptedJsonObject?.add(
                                            "data",
                                            JsonPrimitive(decryptedBoolean)
                                        )
                                    } else if (decryptedJsonPrimitive.isNumber) {
                                        val decryptedNumber = decryptedJsonPrimitive.asNumber
                                        decryptedJsonObject?.add(
                                            "data",
                                            JsonPrimitive(decryptedNumber)
                                        )
                                    } else if (decryptedJsonPrimitive.isString) {
                                        val decryptedString = decryptedJsonPrimitive.asString
                                        decryptedJsonObject?.add(
                                            "data",
                                            JsonPrimitive(decryptedString)
                                        )
                                    } else {
                                        decryptedJsonObject?.add("data", decryptedJsonElement)
                                    }
                                } else {
                                    //其实直接写着一句也行，不关心具体数据类型
                                    decryptedJsonObject?.add("data", decryptedJsonElement)
                                }
                            }
                        }
                        val contentType = responseBody.contentType()
                        val decryptedBody =
                            ResponseBody.create(contentType, decryptedJsonObject.toString())
                        source?.close()
                        return response.newBuilder()
                            .body(decryptedBody)
                            .code(response.code)
                            .build()
                    }
                }
            } catch (e: Exception) {

            }
        }
        return response
    }
}